package com.shioirikukuri.controller;

import com.shioirikukuri.entity.Setmeal;
import com.shioirikukuri.service.ISetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/setmeals")
public class SetmealController {

	@Autowired
	private ISetmealService setmealService;

	@GetMapping
	public ResponseEntity<List<Setmeal>> getAllSetmeals() {
		List<Setmeal> setmeals = setmealService.getAllSetmeals();
		return ResponseEntity.ok(setmeals);
	}

	@GetMapping("/{id}")
	public ResponseEntity<Setmeal> getSetmealById(@PathVariable Long id) {
		Optional<Setmeal> setmeal = setmealService.getSetmealById(id);
		if (setmeal.isPresent()) {
			return ResponseEntity.ok(setmeal.get());
		} else {
			return ResponseEntity.notFound().build();
		}
	}

	@PostMapping
	public ResponseEntity<Setmeal> addSetmeal(@RequestBody SetmealWithFoodIdsDto setmealWithFoodIdsDto) {
		Setmeal newSetmeal = setmealService.addSetmeal(setmealWithFoodIdsDto.getSetmeal(), setmealWithFoodIdsDto.getFoodIds());
		return ResponseEntity.status(201).body(newSetmeal);
	}

	@PutMapping("/{id}")
	public ResponseEntity<Setmeal> updateSetmeal(@PathVariable Long id, @RequestBody SetmealWithFoodIdsDto setmealWithFoodIdsDto) {
		Setmeal updatedSetmeal = setmealService.updateSetmeal(id, setmealWithFoodIdsDto.getSetmeal(), setmealWithFoodIdsDto.getFoodIds());
		return ResponseEntity.ok(updatedSetmeal);
	}

	@DeleteMapping("/{id}")
	public ResponseEntity<Void> deleteSetmeal(@PathVariable Long id) {
		setmealService.deleteSetmeal(id);
		return ResponseEntity.noContent().build();
	}

	// DTO类用于接收包含菜品ID列表的请求体
	public static class SetmealWithFoodIdsDto {
		private Setmeal setmeal;
		private List<Long> foodIds;

		public Setmeal getSetmeal() {
			return setmeal;
		}

		public void setSetmeal(Setmeal setmeal) {
			this.setmeal = setmeal;
		}

		public List<Long> getFoodIds() {
			return foodIds;
		}

		public void setFoodIds(List<Long> foodIds) {
			this.foodIds = foodIds;
		}
	}
}